"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiBaseErrorMidware = exports.ApiBaseError = void 0;
var index_1 = require("./index");
// 错误对象
var ApiBaseError = /** @class */ (function () {
    function ApiBaseError(errMsg, errCode) {
        if (errMsg === void 0) { errMsg = ''; }
        if (errCode === void 0) { errCode = 500; }
        this.errMsg = errMsg;
        this.errCode = errCode;
    }
    return ApiBaseError;
}());
exports.ApiBaseError = ApiBaseError;
var ApiBaseErrorMidware = /** @class */ (function () {
    function ApiBaseErrorMidware() {
    }
    /**
     * 错误处理中间件
    */
    ApiBaseErrorMidware.midware = function (customAjaxResultFail) {
        return function (error, req, res, next) {
            var handleFail = customAjaxResultFail || index_1.ajaxResultFail;
            // 如果错误是字符串将它转成 Result
            if (typeof error === 'string') {
                error = handleFail(error);
            }
            // 触发回调
            ApiBaseErrorMidware.LOG_CALLBACKS.forEach(function (cb) { return cb(error); });
            if (error instanceof index_1.Result) {
                return res.json(error);
            }
            else if (error instanceof ApiBaseError) {
                return res.json(handleFail(error.errMsg, error.errCode));
            }
            else if (error instanceof Error) {
                return res.json(handleFail(error.stack || error.message));
            }
            next();
        };
    };
    /**
     * 设置默认错误日志处理
    */
    ApiBaseErrorMidware.setDefaultLog = function (logPath) {
        if (logPath) {
            index_1.Log.LOG_PATH = logPath;
        }
        ApiBaseErrorMidware.LOG_CALLBACKS.push(index_1.Log.error);
    };
    ApiBaseErrorMidware.LOG_CALLBACKS = [];
    return ApiBaseErrorMidware;
}());
exports.ApiBaseErrorMidware = ApiBaseErrorMidware;
